<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 搜索模块
 *
 * @author      Eden
 * @datetime    2016/12/17 17:29
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Search_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function run($params)
    {

        $send['state'] = false;
        do {

            if (!$this->_checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            // TODO search goods lists


            $this->_afterSearch($params);

        } while(false);
        $this->output->send($send);
    }

    /**
     * After Search
     * @param array $params
     */
    private function _afterSearch($params = array())
    {
        $keyword = trim($params['keyword']);
        $q = $this->db->get_where('search', array('keyword' => $keyword));
        if ($row = $q->row_array()) {
            $this->db->where('keyword', $keyword);
            $times = intval($row['times']) + 1;
            $this->db->update('search', array('times' => $times));
        } else {
            $this->db->insert('search', array(
                'keyword' => $keyword,
                'times' => 1
            ));
        }
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function _checkParams($params = array())
    {
        if ($this->input->method(true) !== 'GET'){
            $this->setError('非法请求');
            return false;
        }

        if (empty($params['keyword'])) {
            $this->setError('缺少必填参数');
            return false;
        }

        return true;
    }

}
